// V8引擎支持 - 简化版本
// 用于动态代码执行和表单处理

export interface V8FormData {
  [key: string]: any
}

export interface V8FieldData {
  [key: string]: any
}

export class V8Engine {
  // 表单数据
  public Form: V8FormData = {}
  // 字段配置
  public Field: V8FieldData = {}
  // 父表单数据
  public ParentForm: V8FormData = {}
  // 父字段配置
  public ParentField: V8FieldData = {}
  // 当前用户
  public CurrentUser: any = {}
  // 系统配置
  public SysConfig: any = {}
  // 客户端类型
  public ClientType: string = ''
  // 表单模式
  public FormMode: string = ''
  // 表单提交动作
  public FormSubmitAction: string = ''
  // 表单外部动作
  public FormOutAction: string = ''
  // 表单提交结果
  public Result: boolean = true
  // 当前值
  public ThisValue: any = {}
  // 子表数据
  public CurrentTableData: any[] = []

  // 初始化
  init(formData: V8FormData, fieldList: any[], formMode: string): V8Engine {
    this.Form = formData
    this.FormMode = formMode
    this.FormSubmitAction =
      formMode === 'Add' ? 'Insert' : formMode === 'Edit' ? 'Update' : 'Delete'
    this.FormOutAction =
      formMode === 'Add' ? 'Insert' : formMode === 'Edit' ? 'Update' : 'Close'
    this.Result = true

    // 处理字段列表
    const fields: V8FieldData = {}
    fieldList.forEach((item) => {
      fields[item.Name] = item
    })
    this.Field = fields

    return this
  }

  // 判断是否为空
  isNull(str: any): boolean {
    if (
      str == null ||
      str == undefined ||
      str === '' ||
      str === 'undefined' ||
      str === 'null' ||
      (Array.isArray(str) && str.length === 0)
    ) {
      return true
    }
    return false
  }

  // 设置表单字段值
  formSet(fieldName: string, value: any): void {
    if (this.Form.hasOwnProperty(fieldName)) {
      this.Form[fieldName] = value
    } else {
      this.Form = {
        ...this.Form,
        [fieldName]: value,
      }
    }
  }

  // 设置字段属性
  fieldSet(fieldName: string, property: string, value: any): void {
    if (this.Field.hasOwnProperty(fieldName)) {
      this.Field[fieldName][property] = value
    } else {
      this.Field = {
        ...this.Field,
        [fieldName]: {
          [property]: value,
        },
      }
    }
  }

  // 生成GUID
  newGuid(): string {
    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(
      /[xy]/g,
      function (c) {
        const r = (Math.random() * 16) | 0
        const v = c == 'x' ? r : (r & 0x3) | 0x8
        return v.toString(16)
      }
    )
  }

  // 工具方法
  method = {
    // 日期格式化
    dateTimeFormat: (time: Date, format: string): string => {
      if (!time || !format) return time.toString()

      const o: Record<string, any> = {
        'M+': time.getMonth() + 1,
        'd+': time.getDate(),
        'h+': time.getHours(),
        'H+': time.getHours(),
        'm+': time.getMinutes(),
        's+': time.getSeconds(),
        'q+': Math.floor((time.getMonth() + 3) / 3),
        S: time.getMilliseconds(),
      }

      if (/(y+)/.test(format)) {
        format = format.replace(
          RegExp.$1,
          (time.getFullYear() + '').substr(4 - RegExp.$1.length)
        )
      }

      for (const k in o) {
        if (new RegExp('(' + k + ')').test(format)) {
          format = format.replace(
            RegExp.$1,
            RegExp.$1.length == 1
              ? o[k]
              : ('00' + o[k]).substr(('' + o[k]).length)
          )
        }
      }
      return format
    },

    // 补齐0
    add0: (value: any, length: number): string => {
      if (!value || !length) return value.toString()
      const count0 = length - value.toString().length
      let result = value.toString()
      for (let i = 0; i < count0; i++) {
        result = '0' + result
      }
      return result
    },
  }

  // 执行V8代码
  async run(v8Code: string): Promise<void> {
    try {
      // 在安全的环境中执行代码
      const func = new Function(
        'V8',
        'Microi',
        `
        (async () => {
          ${v8Code}
        })()
      `
      )
      await func(this, (globalThis as any).Microi)
    } catch (e: any) {
      console.error('执行V8代码出现异常:', e)
      throw new Error('执行V8代码出现异常: ' + (e?.message || e))
    }
  }
}

// 创建全局V8实例
export const V8 = new V8Engine()
